<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
		  <el-breadcrumb-item :to="{ path: '/goods'}">商品列表</el-breadcrumb-item>
		  <el-breadcrumb-item>添加商品</el-breadcrumb-item>
		</el-breadcrumb>
		
		<el-card class="box-card">
			<!-- 警告 -->
			<el-alert
			  title="添加商品信息"
			  type="info"
			  show-icon
			  center
			  :closable="false"
			  >
			</el-alert>
			<!-- 步骤条 -->
			<el-steps  :active="activeIndex - 0" finish-status="success" align-center>
			  <el-step title="基本信息"></el-step>
			  <el-step title="商品参数"></el-step>
			  <el-step title="商品属性"></el-step>
			  <el-step title="商品图片"></el-step>
			  <el-step title="商品内容"></el-step>
			  <el-step title="完成"></el-step>
			</el-steps>
			<!-- 商品添加表单 -->
			<el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px" class="demo-ruleForm" label-position="top">
			  <el-tabs v-model="activeIndex" :tab-position="'left'" style="height:auto;" :before-leave="beforeTabLeave" @tab-click="tabClick">
			    <el-tab-pane label="基本信息">
					<el-form-item label="商品分类" prop="goods_cat">
						 <el-cascader
					    v-model="addForm.goods_cat"
					    :options="catelist"
					    :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id' }"
					    @change="handleChange"></el-cascader>
					</el-form-item>
					<el-form-item label="商品名称" prop="goods_name">
						<el-input v-model="addForm.goods_name"></el-input>
					</el-form-item>
					<el-form-item label="商品价格" prop="goods_price">
						<el-input type="number" v-model="addForm.goods_price"></el-input>
					</el-form-item>
					<el-form-item label="商品重量" prop="goods_weight">
						<el-input type="number" v-model="addForm.goods_weight"></el-input>
					</el-form-item>
					<el-form-item label="商品数量" prop="goods_number">
						<el-input type="number" v-model="addForm.goods_number"></el-input>
					</el-form-item>
					
				</el-tab-pane>
			    <el-tab-pane label="商品参数">
					<el-form-item :label="item1.attr_name" v-for="(item1,i1) in manyTabData" :key="i1">
					
						 <el-checkbox-group v-model="item1.attr_vals">
                           <el-checkbox v-for="(item2,i2) in item1.attr_vals" :key="i2" :label="item2" border></el-checkbox>
                          </el-checkbox-group>
						
					</el-form-item>
				<el-button @click="resetPane" type="primary">重置</el-button>
				</el-tab-pane>
			    <el-tab-pane label="商品属性">
					<el-form-item :label="item3.attr_name" v-for="(item3,i3) in onlyTabData" :key="i3">
						  <el-input v-model="item3.attr_vals" :label="item3.attr_name"></el-input>
					</el-form-item>
				</el-tab-pane>
			    <el-tab-pane label="商品图片">
					 <el-alert
		       	  title="只能上传jpg/png文件，且不超过500kb"
		     	  type="info"
		     	  show-icon
		     	  center
		     	  :closable="true"
				   style="margin:10px;"
		     	  >
		     	</el-alert>  
					<!-- 图片上传 -->
					<el-upload
                     :action="uploadURL"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     list-type="picture"
					 :file-list="picList"
					 :headers="headerObj"
					 :on-success="handleSuccess">
                     <el-button size="small" type="primary" style="margin:10px;">点击上传</el-button>
                   </el-upload>      
				<!-- 警告 -->	               
				</el-tab-pane>
				<el-tab-pane label="商品内容">
					 <quill-editor
                      ref="myQuillEditor"
                      v-model="addForm.goods_introduce"
                    />                  
				</el-tab-pane>
				<el-tab-pane label="数据确认">
					<el-form>
						<el-form-item label="商品名称">
						<el-tag v-if="addForm.goods_name !== ''">{{addForm.goods_name}}</el-tag>	
						<el-tag v-else type="danger">无</el-tag>
					</el-form-item>
										<el-divider></el-divider>
					<el-form-item label="商品价格">
						<el-tag v-if="addForm.goods_price !== ''">{{addForm.goods_price}}</el-tag>
						<el-tag v-else type="danger">无</el-tag>
					</el-form-item>
										<el-divider></el-divider>
					<el-form-item label="商品重量">
						<el-tag v-if="addForm.goods_weight !== ''">{{addForm.goods_weight}} g</el-tag>
						<el-tag v-else type="danger">无</el-tag>
					</el-form-item>
										<el-divider></el-divider>
					<el-form-item label="商品数量">
						<el-tag v-if="addForm.goods_price !== ''">{{addForm.goods_price}}</el-tag>
						<el-tag v-else type="danger">无</el-tag>
					</el-form-item>
					                    <el-divider></el-divider>
					<el-form-item label="参数与属性">
						<el-tag  v-for="item in addForm.attrs" :key="item.id">{{item.attr_name}}{{item.attr_value}}</el-tag>
						<el-tag v-if="addForm.attrs.length === 0" type="danger">无</el-tag>
					</el-form-item>
					                    <el-divider></el-divider>
					<el-form-item label="商品图片">
					  <el-image 
					    class="picList"
					     v-for="item in picList"
						 :key="item.uid"
                         style="width:150px;height:auto;"
                         :src="item.response.data.url" 
                        >
                       </el-image>   
					<el-tag v-if="addForm.pics.length === 0" type="danger">无</el-tag>               
					</el-form-item>
					<el-divider></el-divider>
					<el-form-item label="商品描述">
						{{addForm.goods_introduce}}
						<el-tag v-if="addForm.goods_introduce === ''" type="danger">无</el-tag>    
					</el-form-item>
				</el-form>  
									<el-divider></el-divider>
				 <el-button @click="addGoods">添加商品</el-button>    
				</el-tab-pane>
			  </el-tabs>
			</el-form>  
		</el-card>
		<el-dialog
          title="预览图片"        
          :visible.sync="dialogVisible"
          width="55%"
          :before-close="handleDialogClose">
		 <img :src="prePicPath" class="preimg"  alt="perPic">
        </el-dialog>
		<!-- 添加商品按钮 -->
		
	</div>
</template>

<script>
    import _ from 'lodash'


	export default{
		data(){
			return{
				activeIndex:0,
				catelist:[],
				active:'',
				dialogVisible:false,
				manyTabData:[],
				signMany:false,
				signOnly:false,
				onlyTabData:[],
				prePicPath:'',
				uploadURL:'http://127.0.0.1:8888/api/private/v1/upload',//图片上传地址
				headerObj:{
					Authorization: window.sessionStorage.getItem('token')
				},//图片上传
				addForm:{
					goods_name:'',
					goods_price:'',
					goods_weight:'',
					goods_number:'',
					// 分类数组
					goods_cat:[],
					attrs:[],
					pics:[],
                    goods_introduce:''

				},
				confirmForm:['商品名称',"商品价格","商品重量","商品数量","商品参数","商品属性","商品图片","商品图片"],
				 addFormRules: {
                   goods_name: [
                     { required: true, message: '请输入商品名称', trigger: 'blur' },
                     { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
					],
					goods_price: [
                     { required: true, message: '请输入商品价格', trigger: 'blur' },
                     { min: 1, max: 20, message: '长度在 1 到 10 个字符', trigger: 'blur' }
					],
					goods_weight: [
                     { required: true, message: '请输入商品重量', trigger: 'blur' },
                     { min: 1, max: 20, message: '长度在 1 到 10 个字符', trigger: 'blur' }
					],
					goods_number: [
                     { required: true, message: '请输入商品数量', trigger: 'blur' },
                     { min: 1, max: 20, message: '长度在 1 到 10 个字符', trigger: 'blur' }
					],
					goods_cat: [
                     { required: true, message: '请选择商品分类', trigger: 'blur' }
					]
				 },
				 picList:[]
         
			}
		},
		created() {
			
		},
		methods:{
			handleChange(){
				console.log(this.addForm.goods_cat.length)
				if(this.addForm.goods_cat.length !== 3)
				{
				 this.addForm.goods_cat = []
				 return this.$message.error('只允许选择三级分类')
				}
			},
			async getCateList(){
				const { data:res } = await this.$http.get('categories')
				if( res.meta.status !== 200 )
				return this.$message.error('获取失败')
				this.catelist = res.data
				console.log(this.catelist)
			},
			// tabs切换事件处理
			beforeTabLeave(activeName,oldActiveName){
					console.log(activeName)
					console.log(oldActiveName)

					if(oldActiveName == 0 && this.addForm.goods_cat.length !== 3)
					{
					  this.$message.error('请先选择商品分类')
                      return false
					}
					if(activeName == 1 && this.signMany === false)
					{
						this.active = 'many'
						this.signMany = true
						this.getParamsList()
					}
					else if(activeName == 2 && this.signOnly === false)
					{
						this.active = 'only'
						this.signOnly = true
						this.getParamsList()
					}
					else if(activeName == 5)
					{
						this.addForm.attrs = []
						// 处理动态参数
						this.manyTabData.forEach(item =>{
							let newData = {
								attr_id: item.attr_id,
								attr_value: item.attr_vals.join(',')
							}
							if( newData.attr_value !== '' )
							this.addForm.attrs.push(newData)
						})
					  console.log(this.manyTabData)
						// 处理静态属性
						this.onlyTabData.forEach(item =>{
							let newData = {
								attr_id: item.attr_id,
								attr_value: item.attr_vals
							}
							if( newData.attr_value !== '' )
							this.addForm.attrs.push(newData)
						})
						console.log(this.addForm)
					}
			},
			//获取参数信息
			async getParamsList(){
				
				const { data:res } = await this.$http.get('categories/'+this.addForm.goods_cat[2]+'/attributes',{ params:{ sel:this.active } })
				console.log(res)
				if( res.meta.status !== 200 )
				return this.$message.error(res.meta.msg)
				 console.log(res.data)
				// console.log(this.addForm.attrs)
				if( this.active === 'many' )
				{
				    res.data.forEach( item => { item.attr_vals = ( item.attr_vals !== '' ? item.attr_vals.split(','):[] )})
					this.manyTabData = res.data
				}
				else
					this.onlyTabData = res.data
					console.log(this.onlyTabData)
			},
			//处理图片预览
			handlePreview(file, fileList){
			console.log(fileList)
			this.prePicPath = file.response.data.url
			this.dialogVisible = true
			},
			//处理移除图片操作
			handleRemove(file, fileList){
			console.log(fileList)
			console.log(this.picList)
			const filePath = file.response.data.tmp_path
			const i = this.addForm.pics.findIndex(x => x.pic === filePath)
			this.addForm.pics.splice(i,1)
			console.log(this.addForm)
			},
			// 监听图片上传成功
			handleSuccess(response,file,fileList){
			   const picInfo = { pic:response.data.tmp_path }
			   const picListInfo = { url:response.data.url }
			  this.picList = fileList
			  console.log(fileList)
			   console.log(this.picList)
			  this.addForm.pics.push(picInfo)
			  console.log(this.addForm)
			},
			handleDialogClose(){
				this.dialogVisible = false
			},
			tabClick(){
				console.log(this.activeIndex)
			},
			resetPane(){
				this.signMany = false
				this.getParamsList()
			},
			addGoods(){
				this.$refs.addForm.validate( async valid => {
					if(!valid){
						return this.$message.error('请完善表单后重试')
					}
					
					//执行添加操作
					// 深拷贝 addForm
					const form = _.cloneDeep(this.addForm)
					form.goods_cat = form.goods_cat.join(',')
					
					// 发起添加请求
					const { data:res } = await this.$http.post('goods', form)

					if(res.meta.status !== 201)
					return this.$message.error(res.meta.msg)
					this.$message.success('添加商品成功！')
					this.$router.push('/goods')
					console.log(res)
				})
			},
			indexMethod(index){
				return index
			}
		
		},
		created(){
			this.getCateList()
		}
	}
</script>

<style lang="less" scoped>

.el-tabs{
	margin-top: 20px;
}

.el-input{
	width: 1000px;
	margin-left: 20px;
}
.el-cascader{
	margin-left: 20px;
}
.el-tag{
	margin-left: 10px;
}
.preimg{
	 width:100%; height:auto
}
.el-button{
	margin-top: 20px;
}
.picList{
	margin: 5px;
}
</style>
